// pages/photoDetect/photoDetect.js

const config = require('../../config/config')
const { PhotoService } = require('../../services/photo_service')
const checkAndMake = require('../../utils/imageUtil')

var originalImagePath
var releatedId
var productId
var originalImageUrl
var width
var height
var free
var animationId
var category

Page({
  data: {
    imageData: '',
    top: 0,
    left: 0,
    imageWidth: 0,
    imageHeight: 0,
    orderId: null
  },

  onLoad: function (options) {
    originalImagePath = options.originalImagePath
    productId = options.productId
    releatedId = options.releatedId
    originalImageUrl = options.originalImageUrl
    width = options.width
    height = options.height
    free = options.free
    category = options.category
    if (options.orderId) {
      this.data.orderId = options.orderId
    }

    let fs = wx.getFileSystemManager()
    let data = fs.readFileSync(originalImagePath, 'base64', 0)
    this.checkAndMakePic(releatedId, data)
    this.drawImage(data)
    let selector = wx.createSelectorQuery()
    selector
      .select('#canvas')
      .node()
      .exec((res) => {
        this.canvas = res[0].node
        this.canvas.width = 750
        this.canvas.height = 600
        let ctx = this.canvas.getContext('2d')
        this.animate(this.canvas, ctx, 530, false)
        this.drawBorder(ctx)
      })
  },

  onHide: function () {
    this.canvas.cancelAnimationFrame(animationId)
  },

  // 检测并制作图片
  async checkAndMakePic(id, data) {
		console.log('==checkAndMakePic')
    var res = await checkAndMake(originalImageUrl, id, data)
    let riskResult = res[0]
    let thirdResult = res[1]
		console.log('==thirdResult',thirdResult)
    if (riskResult.action == 'PASSED' && thirdResult.code == 0) {
      let photoService = new PhotoService()
      photoService
        .addPhoto({
          product: productId,
          originalImage: originalImageUrl,
          pass: true,
          picId: thirdResult.data.pic_id,
        })
        .then((res1) => {
					console.log('==addPhoto',res1)
          wx.redirectTo({
            url:
              '/pages/preview/preview?list=' +
                JSON.stringify(thirdResult.data.list) +
                '&pic_id=' +
                thirdResult.data.pic_id +
                '&originalImagePath=' +
                originalImagePath +
                '&originalImageUrl=' +
                originalImageUrl +
                '&productId=' +
                productId +
                '&releatedId=' +
                releatedId +
                '&photoId=' +
                res1.data.id +
                '&category=' +
                category +
                '&orderId=' +
                (this.data.orderId ?? ''),
          }).catch((error) => {
            wx.navigateBack()
          })
        })
    } else {
      let reason = riskResult.action == 'PASSED' ? thirdResult.msg : '图片含有敏感内容'
      let photoService = new PhotoService()
      photoService
        .addPhoto({
          product: productId,
          originalImage: originalImageUrl,
          pass: false,
          reason: reason,
        })
        .then((res) => {
          console.log(res)
          wx.redirectTo({
            url: '/pages/detectFail/detectFail?reason=' + reason + '&originalImagePath=' + originalImagePath,
          })
        })
        .catch((err) => {
          wx.navigateBack()
        })
    }
  },

  drawImage(imageData) {
    wx.getImageInfo({
      src: originalImagePath,
      success: (res) => {
        console.log(res)
        if (res.width / res.height > 400 / 463) {
          let imageWidth = 400
          let imageHeight = (res.height / res.width) * imageWidth
          let x = 175
          let y = 67 + (463 - imageHeight) / 2
          this.setData({
            imageWidth,
            imageHeight,
            top: y,
            left: x,
            imageData: `data:image/${res.type};base64,${imageData}`,
          })
        } else {
          let imageHeight = 463
          let imageWidth = (res.width / res.height) * imageHeight
          let y = 67
          let x = (750 - imageWidth) / 2
          this.setData({
            imageWidth,
            imageHeight,
            top: y,
            left: x,
            imageData: `data:image/${res.type};base64,${imageData}`,
          })
        }
      },
    })
  },

  drawBorder(ctx) {
    // 左上
    ctx.beginPath()
    ctx.strokeStyle = '#C4C6F7'
    ctx.lineWidth = 1
    ctx.moveTo(147, 150)
    ctx.lineTo(147, 40)
    ctx.lineTo(255, 40)
    ctx.stroke()
    ctx.beginPath()
    ctx.strokeStyle = '#555DF5'
    ctx.lineWidth = 5
    ctx.moveTo(147, 60)
    ctx.lineTo(147, 40)
    ctx.lineTo(167, 40)
    ctx.stroke()

    // 右上
    ctx.beginPath()
    ctx.strokeStyle = '#C4C6F7'
    ctx.lineWidth = 1
    ctx.moveTo(495, 40)
    ctx.lineTo(605, 40)
    ctx.lineTo(605, 150)
    ctx.stroke()
    ctx.beginPath()
    ctx.strokeStyle = '#555DF5'
    ctx.lineWidth = 5
    ctx.moveTo(585, 40)
    ctx.lineTo(605, 40)
    ctx.lineTo(605, 60)
    ctx.stroke()

    // 左下
    ctx.beginPath()
    ctx.strokeStyle = '#C4C6F7'
    ctx.lineWidth = 1
    ctx.moveTo(147, 450)
    ctx.lineTo(147, 560)
    ctx.lineTo(255, 560)
    ctx.stroke()
    ctx.beginPath()
    ctx.strokeStyle = '#555DF5'
    ctx.lineWidth = 5
    ctx.moveTo(147, 540)
    ctx.lineTo(147, 560)
    ctx.lineTo(167, 560)
    ctx.stroke()

    // 右下
    ctx.beginPath()
    ctx.strokeStyle = '#C4C6F7'
    ctx.lineWidth = 1
    ctx.moveTo(495, 560)
    ctx.lineTo(605, 560)
    ctx.lineTo(605, 450)
    ctx.stroke()
    ctx.beginPath()
    ctx.strokeStyle = '#555DF5'
    ctx.lineWidth = 5
    ctx.moveTo(585, 560)
    ctx.lineTo(605, 560)
    ctx.lineTo(605, 540)
    ctx.stroke()
  },

  animate(canvas, ctx, y, isDown) {
    ctx.clearRect(175, 60, 420, 475)

    // 遮罩层
    ctx.fillStyle = 'rgba(85, 93, 245, .1)'
    ctx.fillRect(175, 67, 400, 463)
    ctx.clearRect(175, 67, 400, y - 67)

    // 扫描线
    ctx.beginPath()
    ctx.lineWidth = 2
    ctx.strokeStyle = '#555DF5'
    ctx.moveTo(175, y)
    ctx.lineTo(575, y)
    ctx.stroke()
    var that = this

    var onAnimationFrame = function () {
      if (isDown) {
        y += 2
      } else {
        y -= 2
      }
      if (y <= 67) {
        isDown = true
      } else if (y > 530) {
        isDown = false
      }
      that.animate(canvas, ctx, y, isDown)
    }

    animationId = canvas.requestAnimationFrame(onAnimationFrame)
  },
})
